{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch.autograd import Variable\n",
    "from model_2 import WaveNet\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "wav_array = np.load('wav.npy')\n",
    "wav_tensor = torch.from_numpy(wav_array)\n",
    "data = Variable(wav_tensor)  # convert to variable to compute the gradient"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = WaveNet()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer = optim.Adam(model.parameters(), lr=2e-3, eps=1e-4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# lr = 2e-3 * gamma, if epoch < 50\n",
    "# lr = 2e-3 * gamma ** 2, if 50 <= epoch < 150\n",
    "# lr = 2e-3 * gamma ** 3, if epoch >= 250\n",
    "scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[50, 150, 250], gamma=0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 0, loss: 5.568148\n",
      "epoch 1, loss: 5.526599\n",
      "epoch 2, loss: 5.483242\n"
     ]
    }
   ],
   "source": [
    "for epoch in range(3):\n",
    "#     running_loss = []\n",
    "    scheduler.step()  # update lr\n",
    "\n",
    "    inputs = data[:, :-1]  # get the inputs, labels后错inputs 1个值\n",
    "    optimizer.zero_grad()  # zero the parameter gradients\n",
    "    \n",
    "    # forward\n",
    "    logits = model(inputs).squeeze().transpose(0, 1)  # shape (1, 256, n) -> (256, n) -> (n, 256)\n",
    "    labels = data[:, -logits.size(0):].squeeze()  # shape (1, n) -> (n, )\n",
    "    loss = criterion(logits, labels)\n",
    "    \n",
    "    # backward\n",
    "    loss.backward()  # compute the parameter gradients\n",
    "    \n",
    "    # optimize\n",
    "    optimizer.step()  # update the parameters\n",
    "    \n",
    "    print(f'epoch {epoch}, loss: {loss.item():.6f}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
